Note
Click here to download the full example code
DCGAN Tutorial¶
Author: Nathan Inkawhich
Introduction¶
This tutorial will give an introduction to DCGANs through an example. We will train a generative adversarial network (GAN) to generate new celebrities after showing it pictures of many real celebrities. Most of the code here is from the dcgan implementation in pytorch/examples, and this document will give a thorough explanation of the implementation and shed light on how and why this model works. But don’t worry, no prior knowledge of GANs is required, but it may require a first-timer to spend some time reasoning about what is actually happening under the hood. Also, for the sake of time it will help to have a GPU, or two. Lets start from the beginning.
Generative Adversarial Networks¶
What is a GAN?¶
GANs are a framework for teaching a DL model to capture the training data’s distribution so we can generate new data from that same distribution. GANs were invented by Ian Goodfellow in 2014 and first described in the paper Generative Adversarial Nets. They are made of two distinct models, a generator and a discriminator. The job of the generator is to spawn ‘fake’ images that look like the training images. The job of the discriminator is to look at an image and output whether or not it is a real training image or a fake image from the generator. During training, the generator is constantly trying to outsmart the discriminator by generating better and better fakes, while the discriminator is working to become a better detective and correctly classify the real and fake images. The equilibrium of this game is when the generator is generating perfect fakes that look as if they came directly from the training data, and the discriminator is left to always guess at 50% confidence that the generator output is real or fake.
Now, lets define some notation to be used throughout tutorial starting with the discriminator. Let \(x\) be data representing an image. \(D(x)\) is the discriminator network which outputs the (scalar) probability that \(x\) came from training data rather than the generator. Here, since we are dealing with images, the input to \(D(x)\) is an image of CHW size 3x64x64. Intuitively, \(D(x)\) should be HIGH when \(x\) comes from training data and LOW when \(x\) comes from the generator. \(D(x)\) can also be thought of as a traditional binary classifier.
For the generator’s notation, let \(z\) be a latent space vector sampled from a standard normal distribution. \(G(z)\) represents the generator function which maps the latent vector \(z\) to data-space. The goal of \(G\) is to estimate the distribution that the training data comes from (\(p_{data}\)) so it can generate fake samples from that estimated distribution (\(p_g\)).
So, \(D(G(z))\) is the probability (scalar) that the output of the generator \(G\) is a real image. As described in Goodfellow’s paper, \(D\) and \(G\) play a minimax game in which \(D\) tries to maximize the probability it correctly classifies reals and fakes (\(logD(x)\)), and \(G\) tries to minimize the probability that \(D\) will predict its outputs are fake (\(log(1-D(G(z)))\)). From the paper, the GAN loss function is
In theory, the solution to this minimax game is where \(p_g = p_{data}\), and the discriminator guesses randomly if the inputs are real or fake. However, the convergence theory of GANs is still being actively researched and in reality models do not always train to this point.
What is a DCGAN?¶
A DCGAN is a direct extension of the GAN described above, except that it explicitly uses convolutional and convolutional-transpose layers in the discriminator and generator, respectively. It was first described by Radford et. al. in the paper Unsupervised Representation Learning With Deep Convolutional Generative Adversarial Networks. The discriminator is made up of strided convolution layers, batch norm layers, and LeakyReLU activations. The input is a 3x64x64 input image and the output is a scalar probability that the input is from the real data distribution. The generator is comprised of convolutional-transpose layers, batch norm layers, and ReLU activations. The input is a latent vector, \(z\), that is drawn from a standard normal distribution and the output is a 3x64x64 RGB image. The strided conv-transpose layers allow the latent vector to be transformed into a volume with the same shape as an image. In the paper, the authors also give some tips about how to setup the optimizers, how to calculate the loss functions, and how to initialize the model weights, all of which will be explained in the coming sections.
from __future__ import print_function
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
# Set random seed for reproducibility
manualSeed = 999
#manualSeed = random.randint(1, 10000) # use if you want new results
print("Random Seed: ", manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
Random Seed: 999
<torch._C.Generator object at 0x7f8273c87730>
Inputs¶
Let’s define some inputs for the run:
dataroot - the path to the root of the dataset folder. We will talk more about the dataset in the next section
workers - the number of worker threads for loading the data with the DataLoader
batch_size - the batch size used in training. The DCGAN paper uses a batch size of 128
image_size - the spatial size of the images used for training. This implementation defaults to 64x64. If another size is desired, the structures of D and G must be changed. See here for more details
nc - number of color channels in the input images. For color images this is 3
nz - length of latent vector
ngf - relates to the depth of feature maps carried through the generator
ndf - sets the depth of feature maps propagated through the discriminator
num_epochs - number of training epochs to run. Training for longer will probably lead to better results but will also take much longer
lr - learning rate for training. As described in the DCGAN paper, this number should be 0.0002
beta1 - beta1 hyperparameter for Adam optimizers. As described in paper, this number should be 0.5
ngpu - number of GPUs available. If this is 0, code will run in CPU mode. If this number is greater than 0 it will run on that number of GPUs
# Root directory for dataset
dataroot = "data/celeba"
# Number of workers for dataloader
workers = 2
# Batch size during training
batch_size = 128
# Spatial size of training images. All images will be resized to this
# size using a transformer.
image_size = 64
# Number of channels in the training images. For color images this is 3
nc = 3
# Size of z latent vector (i.e. size of generator input)
nz = 100
# Size of feature maps in generator
ngf = 64
# Size of feature maps in discriminator
ndf = 64
# Number of training epochs
num_epochs = 5
# Learning rate for optimizers
lr = 0.0002
# Beta1 hyperparam for Adam optimizers
beta1 = 0.5
# Number of GPUs available. Use 0 for CPU mode.
ngpu = 1
Data¶
In this tutorial we will use the Celeb-A Faces dataset which can be downloaded at the linked site, or in Google Drive. The dataset will download as a file named img_align_celeba.zip. Once downloaded, create a directory named celeba and extract the zip file into that directory. Then, set the dataroot input for this notebook to the celeba directory you just created. The resulting directory structure should be:
/path/to/celeba
-> img_align_celeba
-> 188242.jpg
-> 173822.jpg
-> 284702.jpg
-> 537394.jpg
...
This is an important step because we will be using the ImageFolder dataset class, which requires there to be subdirectories in the dataset’s root folder. Now, we can create the dataset, create the dataloader, set the device to run on, and finally visualize some of the training data.
# We can use an image folder dataset the way we have it setup.
# Create the dataset
dataset = dset.ImageFolder(root=dataroot,
transform=transforms.Compose([
transforms.Resize(image_size),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
]))
# Create the dataloader
dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
shuffle=True, num_workers=workers)
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
# Plot some training images
real_batch = next(iter(dataloader))
plt.figure(figsize=(8,8))
plt.axis("off")
plt.title("Training Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))

<matplotlib.image.AxesImage object at 0x7f8253600160>
Implementation¶
With our input parameters set and the dataset prepared, we can now get into the implementation. We will start with the weight initialization strategy, then talk about the generator, discriminator, loss functions, and training loop in detail.
Weight Initialization¶
From the DCGAN paper, the authors specify that all model weights shall
be randomly initialized from a Normal distribution with mean=0,
stdev=0.02. The weights_init function takes an initialized model as
input and reinitializes all convolutional, convolutional-transpose, and
batch normalization layers to meet this criteria. This function is
applied to the models immediately after initialization.
# custom weights initialization called on netG and netD
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
Generator¶
The generator, \(G\), is designed to map the latent space vector (\(z\)) to data-space. Since our data are images, converting \(z\) to data-space means ultimately creating a RGB image with the same size as the training images (i.e. 3x64x64). In practice, this is accomplished through a series of strided two dimensional convolutional transpose layers, each paired with a 2d batch norm layer and a relu activation. The output of the generator is fed through a tanh function to return it to the input data range of \([-1,1]\). It is worth noting the existence of the batch norm functions after the conv-transpose layers, as this is a critical contribution of the DCGAN paper. These layers help with the flow of gradients during training. An image of the generator from the DCGAN paper is shown below.
Notice, how the inputs we set in the input section (nz, ngf, and nc) influence the generator architecture in code. nz is the length of the z input vector, ngf relates to the size of the feature maps that are propagated through the generator, and nc is the number of channels in the output image (set to 3 for RGB images). Below is the code for the generator.
# Generator Code
class Generator(nn.Module):
def __init__(self, ngpu):
super(Generator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 8),
nn.ReLU(True),
# state size. (ngf*8) x 4 x 4
nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
# state size. (ngf*4) x 8 x 8
nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
# state size. (ngf*2) x 16 x 16
nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
# state size. (ngf) x 32 x 32
nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),
nn.Tanh()
# state size. (nc) x 64 x 64
)
def forward(self, input):
return self.main(input)
Now, we can instantiate the generator and apply the weights_init
function. Check out the printed model to see how the generator object is
structured.
# Create the generator
netG = Generator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netG = nn.DataParallel(netG, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.02.
netG.apply(weights_init)
# Print the model
print(netG)
Generator(
(main): Sequential(
(0): ConvTranspose2d(100, 512, kernel_size=(4, 4), stride=(1, 1), bias=False)
(1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU(inplace=True)
(3): ConvTranspose2d(512, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(4): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(5): ReLU(inplace=True)
(6): ConvTranspose2d(256, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(7): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(8): ReLU(inplace=True)
(9): ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(10): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(11): ReLU(inplace=True)
(12): ConvTranspose2d(64, 3, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(13): Tanh()
)
)
Discriminator¶
As mentioned, the discriminator, \(D\), is a binary classification network that takes an image as input and outputs a scalar probability that the input image is real (as opposed to fake). Here, \(D\) takes a 3x64x64 input image, processes it through a series of Conv2d, BatchNorm2d, and LeakyReLU layers, and outputs the final probability through a Sigmoid activation function. This architecture can be extended with more layers if necessary for the problem, but there is significance to the use of the strided convolution, BatchNorm, and LeakyReLUs. The DCGAN paper mentions it is a good practice to use strided convolution rather than pooling to downsample because it lets the network learn its own pooling function. Also batch norm and leaky relu functions promote healthy gradient flow which is critical for the learning process of both \(G\) and \(D\).
Discriminator Code
class Discriminator(nn.Module):
def __init__(self, ngpu):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is (nc) x 64 x 64
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf) x 32 x 32
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*2) x 16 x 16
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*4) x 8 x 8
nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 8),
nn.LeakyReLU(0.2, inplace=True),
# state size. (ndf*8) x 4 x 4
nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),
nn.Sigmoid()
)
def forward(self, input):
return self.main(input)
Now, as with the generator, we can create the discriminator, apply the
weights_init function, and print the model’s structure.
# Create the Discriminator
netD = Discriminator(ngpu).to(device)
# Handle multi-gpu if desired
if (device.type == 'cuda') and (ngpu > 1):
netD = nn.DataParallel(netD, list(range(ngpu)))
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
netD.apply(weights_init)
# Print the model
print(netD)
Discriminator(
(main): Sequential(
(0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): LeakyReLU(negative_slope=0.2, inplace=True)
(2): Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(3): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(4): LeakyReLU(negative_slope=0.2, inplace=True)
(5): Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(6): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(7): LeakyReLU(negative_slope=0.2, inplace=True)
(8): Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(9): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(10): LeakyReLU(negative_slope=0.2, inplace=True)
(11): Conv2d(512, 1, kernel_size=(4, 4), stride=(1, 1), bias=False)
(12): Sigmoid()
)
)
Loss Functions and Optimizers¶
With \(D\) and \(G\) setup, we can specify how they learn through the loss functions and optimizers. We will use the Binary Cross Entropy loss (BCELoss) function which is defined in PyTorch as:
Notice how this function provides the calculation of both log components in the objective function (i.e. \(log(D(x))\) and \(log(1-D(G(z)))\)). We can specify what part of the BCE equation to use with the \(y\) input. This is accomplished in the training loop which is coming up soon, but it is important to understand how we can choose which component we wish to calculate just by changing \(y\) (i.e. GT labels).
Next, we define our real label as 1 and the fake label as 0. These labels will be used when calculating the losses of \(D\) and \(G\), and this is also the convention used in the original GAN paper. Finally, we set up two separate optimizers, one for \(D\) and one for \(G\). As specified in the DCGAN paper, both are Adam optimizers with learning rate 0.0002 and Beta1 = 0.5. For keeping track of the generator’s learning progression, we will generate a fixed batch of latent vectors that are drawn from a Gaussian distribution (i.e. fixed_noise) . In the training loop, we will periodically input this fixed_noise into \(G\), and over the iterations we will see images form out of the noise.
# Initialize BCELoss function
criterion = nn.BCELoss()
# Create batch of latent vectors that we will use to visualize
# the progression of the generator
fixed_noise = torch.randn(64, nz, 1, 1, device=device)
# Establish convention for real and fake labels during training
real_label = 1.
fake_label = 0.
# Setup Adam optimizers for both G and D
optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
Training¶
Finally, now that we have all of the parts of the GAN framework defined, we can train it. Be mindful that training GANs is somewhat of an art form, as incorrect hyperparameter settings lead to mode collapse with little explanation of what went wrong. Here, we will closely follow Algorithm 1 from Goodfellow’s paper, while abiding by some of the best practices shown in ganhacks. Namely, we will “construct different mini-batches for real and fake” images, and also adjust G’s objective function to maximize \(logD(G(z))\). Training is split up into two main parts. Part 1 updates the Discriminator and Part 2 updates the Generator.
Part 1 - Train the Discriminator
Recall, the goal of training the discriminator is to maximize the probability of correctly classifying a given input as real or fake. In terms of Goodfellow, we wish to “update the discriminator by ascending its stochastic gradient”. Practically, we want to maximize \(log(D(x)) + log(1-D(G(z)))\). Due to the separate mini-batch suggestion from ganhacks, we will calculate this in two steps. First, we will construct a batch of real samples from the training set, forward pass through \(D\), calculate the loss (\(log(D(x))\)), then calculate the gradients in a backward pass. Secondly, we will construct a batch of fake samples with the current generator, forward pass this batch through \(D\), calculate the loss (\(log(1-D(G(z)))\)), and accumulate the gradients with a backward pass. Now, with the gradients accumulated from both the all-real and all-fake batches, we call a step of the Discriminator’s optimizer.
Part 2 - Train the Generator
As stated in the original paper, we want to train the Generator by minimizing \(log(1-D(G(z)))\) in an effort to generate better fakes. As mentioned, this was shown by Goodfellow to not provide sufficient gradients, especially early in the learning process. As a fix, we instead wish to maximize \(log(D(G(z)))\). In the code we accomplish this by: classifying the Generator output from Part 1 with the Discriminator, computing G’s loss using real labels as GT, computing G’s gradients in a backward pass, and finally updating G’s parameters with an optimizer step. It may seem counter-intuitive to use the real labels as GT labels for the loss function, but this allows us to use the \(log(x)\) part of the BCELoss (rather than the \(log(1-x)\) part) which is exactly what we want.
Finally, we will do some statistic reporting and at the end of each epoch we will push our fixed_noise batch through the generator to visually track the progress of G’s training. The training statistics reported are:
Loss_D - discriminator loss calculated as the sum of losses for the all real and all fake batches (\(log(D(x)) + log(1 - D(G(z)))\)).
Loss_G - generator loss calculated as \(log(D(G(z)))\)
D(x) - the average output (across the batch) of the discriminator for the all real batch. This should start close to 1 then theoretically converge to 0.5 when G gets better. Think about why this is.
D(G(z)) - average discriminator outputs for the all fake batch. The first number is before D is updated and the second number is after D is updated. These numbers should start near 0 and converge to 0.5 as G gets better. Think about why this is.
Note: This step might take a while, depending on how many epochs you run and if you removed some data from the dataset.
# Training Loop
# Lists to keep track of progress
img_list = []
G_losses = []
D_losses = []
iters = 0
print("Starting Training Loop...")
# For each epoch
for epoch in range(num_epochs):
# For each batch in the dataloader
for i, data in enumerate(dataloader, 0):
############################
# (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))
###########################
## Train with all-real batch
netD.zero_grad()
# Format batch
real_cpu = data[0].to(device)
b_size = real_cpu.size(0)
label = torch.full((b_size,), real_label, dtype=torch.float, device=device)
# Forward pass real batch through D
output = netD(real_cpu).view(-1)
# Calculate loss on all-real batch
errD_real = criterion(output, label)
# Calculate gradients for D in backward pass
errD_real.backward()
D_x = output.mean().item()
## Train with all-fake batch
# Generate batch of latent vectors
noise = torch.randn(b_size, nz, 1, 1, device=device)
# Generate fake image batch with G
fake = netG(noise)
label.fill_(fake_label)
# Classify all fake batch with D
output = netD(fake.detach()).view(-1)
# Calculate D's loss on the all-fake batch
errD_fake = criterion(output, label)
# Calculate the gradients for this batch, accumulated (summed) with previous gradients
errD_fake.backward()
D_G_z1 = output.mean().item()
# Compute error of D as sum over the fake and the real batches
errD = errD_real + errD_fake
# Update D
optimizerD.step()
############################
# (2) Update G network: maximize log(D(G(z)))
###########################
netG.zero_grad()
label.fill_(real_label) # fake labels are real for generator cost
# Since we just updated D, perform another forward pass of all-fake batch through D
output = netD(fake).view(-1)
# Calculate G's loss based on this output
errG = criterion(output, label)
# Calculate gradients for G
errG.backward()
D_G_z2 = output.mean().item()
# Update G
optimizerG.step()
# Output training stats
if i % 50 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
% (epoch, num_epochs, i, len(dataloader),
errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
# Save Losses for plotting later
G_losses.append(errG.item())
D_losses.append(errD.item())
# Check how the generator is doing by saving G's output on fixed_noise
if (iters % 500 == 0) or ((epoch == num_epochs-1) and (i == len(dataloader)-1)):
with torch.no_grad():
fake = netG(fixed_noise).detach().cpu()
img_list.append(vutils.make_grid(fake, padding=2, normalize=True))
iters += 1
Starting Training Loop...
[0/5][0/1583] Loss_D: 1.6264 Loss_G: 5.5240 D(x): 0.5733 D(G(z)): 0.5501 / 0.0065
[0/5][50/1583] Loss_D: 0.3166 Loss_G: 14.1736 D(x): 0.9588 D(G(z)): 0.1866 / 0.0000
[0/5][100/1583] Loss_D: 0.2248 Loss_G: 9.1165 D(x): 0.9761 D(G(z)): 0.1569 / 0.0007
[0/5][150/1583] Loss_D: 0.6076 Loss_G: 7.8969 D(x): 0.9685 D(G(z)): 0.3982 / 0.0008
[0/5][200/1583] Loss_D: 0.2348 Loss_G: 4.6866 D(x): 0.9173 D(G(z)): 0.1070 / 0.0282
[0/5][250/1583] Loss_D: 0.4260 Loss_G: 4.9257 D(x): 0.8556 D(G(z)): 0.1030 / 0.0123
[0/5][300/1583] Loss_D: 1.2321 Loss_G: 5.2986 D(x): 0.4384 D(G(z)): 0.0064 / 0.0164
[0/5][350/1583] Loss_D: 0.4066 Loss_G: 3.7959 D(x): 0.8266 D(G(z)): 0.1404 / 0.0333
[0/5][400/1583] Loss_D: 0.4002 Loss_G: 3.6595 D(x): 0.7934 D(G(z)): 0.0973 / 0.0384
[0/5][450/1583] Loss_D: 0.7030 Loss_G: 4.4851 D(x): 0.6474 D(G(z)): 0.0199 / 0.0238
[0/5][500/1583] Loss_D: 0.6987 Loss_G: 6.5543 D(x): 0.9106 D(G(z)): 0.3815 / 0.0031
[0/5][550/1583] Loss_D: 0.3840 Loss_G: 4.7709 D(x): 0.7734 D(G(z)): 0.0278 / 0.0175
[0/5][600/1583] Loss_D: 0.4218 Loss_G: 4.9004 D(x): 0.8267 D(G(z)): 0.1345 / 0.0120
[0/5][650/1583] Loss_D: 0.7014 Loss_G: 3.6363 D(x): 0.6900 D(G(z)): 0.1124 / 0.0656
[0/5][700/1583] Loss_D: 0.5634 Loss_G: 3.3720 D(x): 0.7400 D(G(z)): 0.0920 / 0.0781
[0/5][750/1583] Loss_D: 0.4983 Loss_G: 5.3880 D(x): 0.7113 D(G(z)): 0.0097 / 0.0099
[0/5][800/1583] Loss_D: 1.0523 Loss_G: 8.8866 D(x): 0.9758 D(G(z)): 0.5134 / 0.0005
[0/5][850/1583] Loss_D: 0.2489 Loss_G: 3.1099 D(x): 0.8686 D(G(z)): 0.0727 / 0.0792
[0/5][900/1583] Loss_D: 0.3398 Loss_G: 4.2456 D(x): 0.8451 D(G(z)): 0.0992 / 0.0310
[0/5][950/1583] Loss_D: 0.8127 Loss_G: 6.8214 D(x): 0.8803 D(G(z)): 0.4116 / 0.0028
[0/5][1000/1583] Loss_D: 0.2528 Loss_G: 4.6453 D(x): 0.8510 D(G(z)): 0.0397 / 0.0155
[0/5][1050/1583] Loss_D: 1.3878 Loss_G: 0.2321 D(x): 0.3814 D(G(z)): 0.0123 / 0.8308
[0/5][1100/1583] Loss_D: 0.3517 Loss_G: 4.1190 D(x): 0.8488 D(G(z)): 0.1375 / 0.0250
[0/5][1150/1583] Loss_D: 0.2792 Loss_G: 4.7103 D(x): 0.8893 D(G(z)): 0.1233 / 0.0171
[0/5][1200/1583] Loss_D: 0.3293 Loss_G: 3.3306 D(x): 0.8219 D(G(z)): 0.0909 / 0.0563
[0/5][1250/1583] Loss_D: 0.5811 Loss_G: 4.5197 D(x): 0.8163 D(G(z)): 0.2392 / 0.0196
[0/5][1300/1583] Loss_D: 0.7333 Loss_G: 2.4417 D(x): 0.5746 D(G(z)): 0.0215 / 0.1236
[0/5][1350/1583] Loss_D: 0.6001 Loss_G: 3.5677 D(x): 0.7904 D(G(z)): 0.2377 / 0.0405
[0/5][1400/1583] Loss_D: 0.5291 Loss_G: 5.9752 D(x): 0.8636 D(G(z)): 0.2676 / 0.0056
[0/5][1450/1583] Loss_D: 1.2008 Loss_G: 2.2220 D(x): 0.4137 D(G(z)): 0.0061 / 0.1664
[0/5][1500/1583] Loss_D: 1.2848 Loss_G: 2.5048 D(x): 0.4273 D(G(z)): 0.0036 / 0.1387
[0/5][1550/1583] Loss_D: 0.6659 Loss_G: 4.8863 D(x): 0.8725 D(G(z)): 0.3517 / 0.0115
[1/5][0/1583] Loss_D: 0.9155 Loss_G: 9.8556 D(x): 0.9846 D(G(z)): 0.5164 / 0.0002
[1/5][50/1583] Loss_D: 0.6010 Loss_G: 2.6675 D(x): 0.6752 D(G(z)): 0.0513 / 0.1078
[1/5][100/1583] Loss_D: 0.7706 Loss_G: 4.3644 D(x): 0.8314 D(G(z)): 0.3487 / 0.0298
[1/5][150/1583] Loss_D: 0.2704 Loss_G: 5.0408 D(x): 0.9354 D(G(z)): 0.1621 / 0.0115
[1/5][200/1583] Loss_D: 0.7224 Loss_G: 2.6034 D(x): 0.5951 D(G(z)): 0.0365 / 0.1405
[1/5][250/1583] Loss_D: 0.5326 Loss_G: 4.2307 D(x): 0.8282 D(G(z)): 0.2371 / 0.0234
[1/5][300/1583] Loss_D: 1.8246 Loss_G: 7.7157 D(x): 0.9778 D(G(z)): 0.7818 / 0.0009
[1/5][350/1583] Loss_D: 1.0152 Loss_G: 1.8776 D(x): 0.4876 D(G(z)): 0.0521 / 0.2294
[1/5][400/1583] Loss_D: 0.3108 Loss_G: 4.3154 D(x): 0.8814 D(G(z)): 0.1324 / 0.0241
[1/5][450/1583] Loss_D: 1.8964 Loss_G: 1.1665 D(x): 0.2566 D(G(z)): 0.0160 / 0.4194
[1/5][500/1583] Loss_D: 0.6260 Loss_G: 2.6340 D(x): 0.6355 D(G(z)): 0.0467 / 0.1347
[1/5][550/1583] Loss_D: 0.4837 Loss_G: 3.0736 D(x): 0.7811 D(G(z)): 0.1567 / 0.0736
[1/5][600/1583] Loss_D: 0.3479 Loss_G: 3.0841 D(x): 0.7973 D(G(z)): 0.0758 / 0.0692
[1/5][650/1583] Loss_D: 0.4993 Loss_G: 4.2858 D(x): 0.8813 D(G(z)): 0.2629 / 0.0246
[1/5][700/1583] Loss_D: 0.5904 Loss_G: 2.4901 D(x): 0.6613 D(G(z)): 0.0628 / 0.1233
[1/5][750/1583] Loss_D: 0.6480 Loss_G: 1.9831 D(x): 0.6369 D(G(z)): 0.0689 / 0.2029
[1/5][800/1583] Loss_D: 0.5707 Loss_G: 5.4357 D(x): 0.9039 D(G(z)): 0.3237 / 0.0076
[1/5][850/1583] Loss_D: 0.5578 Loss_G: 2.3072 D(x): 0.6808 D(G(z)): 0.0531 / 0.1471
[1/5][900/1583] Loss_D: 0.5511 Loss_G: 2.9340 D(x): 0.7671 D(G(z)): 0.1879 / 0.0811
[1/5][950/1583] Loss_D: 0.4678 Loss_G: 2.0661 D(x): 0.7080 D(G(z)): 0.0702 / 0.1668
[1/5][1000/1583] Loss_D: 0.3698 Loss_G: 4.1068 D(x): 0.9149 D(G(z)): 0.2174 / 0.0259
[1/5][1050/1583] Loss_D: 0.8320 Loss_G: 2.0853 D(x): 0.5494 D(G(z)): 0.0328 / 0.1848
[1/5][1100/1583] Loss_D: 0.6981 Loss_G: 1.5759 D(x): 0.6276 D(G(z)): 0.1326 / 0.2576
[1/5][1150/1583] Loss_D: 0.8312 Loss_G: 5.7255 D(x): 0.9624 D(G(z)): 0.4929 / 0.0061
[1/5][1200/1583] Loss_D: 0.6405 Loss_G: 1.7927 D(x): 0.6550 D(G(z)): 0.0823 / 0.2200
[1/5][1250/1583] Loss_D: 1.0101 Loss_G: 2.1859 D(x): 0.4516 D(G(z)): 0.0321 / 0.1840
[1/5][1300/1583] Loss_D: 0.3844 Loss_G: 3.3999 D(x): 0.8501 D(G(z)): 0.1590 / 0.0524
[1/5][1350/1583] Loss_D: 1.0527 Loss_G: 5.8441 D(x): 0.8963 D(G(z)): 0.5335 / 0.0076
[1/5][1400/1583] Loss_D: 1.5410 Loss_G: 6.9794 D(x): 0.9694 D(G(z)): 0.7054 / 0.0027
[1/5][1450/1583] Loss_D: 0.5310 Loss_G: 3.8873 D(x): 0.9324 D(G(z)): 0.3287 / 0.0300
[1/5][1500/1583] Loss_D: 1.4036 Loss_G: 6.2536 D(x): 0.9532 D(G(z)): 0.6670 / 0.0044
[1/5][1550/1583] Loss_D: 1.4461 Loss_G: 5.7024 D(x): 0.9538 D(G(z)): 0.6565 / 0.0061
[2/5][0/1583] Loss_D: 0.3074 Loss_G: 3.4085 D(x): 0.8385 D(G(z)): 0.0948 / 0.0489
[2/5][50/1583] Loss_D: 0.6807 Loss_G: 4.6771 D(x): 0.9344 D(G(z)): 0.4199 / 0.0139
[2/5][100/1583] Loss_D: 0.7405 Loss_G: 3.3403 D(x): 0.8685 D(G(z)): 0.3753 / 0.0530
[2/5][150/1583] Loss_D: 0.4178 Loss_G: 2.4295 D(x): 0.7929 D(G(z)): 0.1439 / 0.1197
[2/5][200/1583] Loss_D: 0.5381 Loss_G: 3.0876 D(x): 0.8316 D(G(z)): 0.2506 / 0.0675
[2/5][250/1583] Loss_D: 0.5362 Loss_G: 3.7522 D(x): 0.8975 D(G(z)): 0.3091 / 0.0372
[2/5][300/1583] Loss_D: 0.4998 Loss_G: 2.1439 D(x): 0.7604 D(G(z)): 0.1683 / 0.1440
[2/5][350/1583] Loss_D: 0.5560 Loss_G: 3.0487 D(x): 0.8448 D(G(z)): 0.2828 / 0.0644
[2/5][400/1583] Loss_D: 2.1153 Loss_G: 8.0539 D(x): 0.9776 D(G(z)): 0.8268 / 0.0008
[2/5][450/1583] Loss_D: 0.5840 Loss_G: 3.5864 D(x): 0.8675 D(G(z)): 0.3167 / 0.0387
[2/5][500/1583] Loss_D: 2.1049 Loss_G: 0.0561 D(x): 0.1846 D(G(z)): 0.0089 / 0.9478
[2/5][550/1583] Loss_D: 0.3198 Loss_G: 3.2961 D(x): 0.8510 D(G(z)): 0.1283 / 0.0536
[2/5][600/1583] Loss_D: 1.0186 Loss_G: 1.2606 D(x): 0.4612 D(G(z)): 0.0320 / 0.3488
[2/5][650/1583] Loss_D: 0.4226 Loss_G: 2.5599 D(x): 0.8223 D(G(z)): 0.1715 / 0.1020
[2/5][700/1583] Loss_D: 0.5622 Loss_G: 2.2961 D(x): 0.7669 D(G(z)): 0.2153 / 0.1329
[2/5][750/1583] Loss_D: 0.8805 Loss_G: 0.8628 D(x): 0.5613 D(G(z)): 0.1660 / 0.4664
[2/5][800/1583] Loss_D: 0.4994 Loss_G: 2.3043 D(x): 0.7555 D(G(z)): 0.1581 / 0.1285
[2/5][850/1583] Loss_D: 0.6051 Loss_G: 2.8590 D(x): 0.8222 D(G(z)): 0.2808 / 0.0800
[2/5][900/1583] Loss_D: 0.3870 Loss_G: 2.7156 D(x): 0.8332 D(G(z)): 0.1650 / 0.0885
[2/5][950/1583] Loss_D: 0.7781 Loss_G: 2.1594 D(x): 0.6447 D(G(z)): 0.2054 / 0.1595
[2/5][1000/1583] Loss_D: 0.4971 Loss_G: 2.2118 D(x): 0.7927 D(G(z)): 0.1961 / 0.1351
[2/5][1050/1583] Loss_D: 0.5752 Loss_G: 2.8620 D(x): 0.8614 D(G(z)): 0.3128 / 0.0719
[2/5][1100/1583] Loss_D: 0.9324 Loss_G: 4.3908 D(x): 0.9711 D(G(z)): 0.5508 / 0.0185
[2/5][1150/1583] Loss_D: 0.4562 Loss_G: 3.1139 D(x): 0.8897 D(G(z)): 0.2562 / 0.0606
[2/5][1200/1583] Loss_D: 0.5230 Loss_G: 2.5300 D(x): 0.7720 D(G(z)): 0.1934 / 0.1020
[2/5][1250/1583] Loss_D: 0.5530 Loss_G: 1.9923 D(x): 0.7155 D(G(z)): 0.1513 / 0.1688
[2/5][1300/1583] Loss_D: 0.5469 Loss_G: 3.2999 D(x): 0.8638 D(G(z)): 0.2851 / 0.0507
[2/5][1350/1583] Loss_D: 0.6665 Loss_G: 1.9663 D(x): 0.7196 D(G(z)): 0.2310 / 0.1769
[2/5][1400/1583] Loss_D: 1.1024 Loss_G: 4.6953 D(x): 0.9316 D(G(z)): 0.5883 / 0.0144
[2/5][1450/1583] Loss_D: 0.8249 Loss_G: 4.2287 D(x): 0.9466 D(G(z)): 0.4732 / 0.0229
[2/5][1500/1583] Loss_D: 0.3960 Loss_G: 2.9526 D(x): 0.8312 D(G(z)): 0.1706 / 0.0686
[2/5][1550/1583] Loss_D: 0.5770 Loss_G: 2.3028 D(x): 0.6739 D(G(z)): 0.1109 / 0.1319
[3/5][0/1583] Loss_D: 0.5828 Loss_G: 2.3885 D(x): 0.6337 D(G(z)): 0.0684 / 0.1220
[3/5][50/1583] Loss_D: 0.7372 Loss_G: 1.1567 D(x): 0.5665 D(G(z)): 0.0958 / 0.3543
[3/5][100/1583] Loss_D: 0.6391 Loss_G: 3.1309 D(x): 0.8558 D(G(z)): 0.3393 / 0.0577
[3/5][150/1583] Loss_D: 0.4596 Loss_G: 3.2693 D(x): 0.8727 D(G(z)): 0.2560 / 0.0493
[3/5][200/1583] Loss_D: 0.6538 Loss_G: 2.9360 D(x): 0.8359 D(G(z)): 0.3360 / 0.0766
[3/5][250/1583] Loss_D: 0.9843 Loss_G: 2.0213 D(x): 0.4384 D(G(z)): 0.0242 / 0.1835
[3/5][300/1583] Loss_D: 0.5058 Loss_G: 2.5947 D(x): 0.8391 D(G(z)): 0.2477 / 0.0967
[3/5][350/1583] Loss_D: 0.8828 Loss_G: 3.8930 D(x): 0.8201 D(G(z)): 0.4475 / 0.0304
[3/5][400/1583] Loss_D: 0.6126 Loss_G: 2.0969 D(x): 0.6764 D(G(z)): 0.1529 / 0.1615
[3/5][450/1583] Loss_D: 1.0092 Loss_G: 4.4471 D(x): 0.8968 D(G(z)): 0.5356 / 0.0176
[3/5][500/1583] Loss_D: 0.6079 Loss_G: 2.2764 D(x): 0.7320 D(G(z)): 0.2142 / 0.1287
[3/5][550/1583] Loss_D: 0.5290 Loss_G: 2.4479 D(x): 0.8310 D(G(z)): 0.2599 / 0.1107
[3/5][600/1583] Loss_D: 0.6309 Loss_G: 3.2739 D(x): 0.8477 D(G(z)): 0.3269 / 0.0567
[3/5][650/1583] Loss_D: 0.4916 Loss_G: 2.4001 D(x): 0.7280 D(G(z)): 0.1248 / 0.1184
[3/5][700/1583] Loss_D: 0.5672 Loss_G: 2.1005 D(x): 0.6675 D(G(z)): 0.1000 / 0.1604
[3/5][750/1583] Loss_D: 0.7592 Loss_G: 3.3171 D(x): 0.9117 D(G(z)): 0.4475 / 0.0499
[3/5][800/1583] Loss_D: 0.6332 Loss_G: 1.6712 D(x): 0.6585 D(G(z)): 0.1446 / 0.2215
[3/5][850/1583] Loss_D: 1.2410 Loss_G: 4.5827 D(x): 0.9087 D(G(z)): 0.6146 / 0.0171
[3/5][900/1583] Loss_D: 0.4706 Loss_G: 2.6556 D(x): 0.8103 D(G(z)): 0.2044 / 0.0888
[3/5][950/1583] Loss_D: 0.8890 Loss_G: 1.2051 D(x): 0.4701 D(G(z)): 0.0237 / 0.3503
[3/5][1000/1583] Loss_D: 0.5797 Loss_G: 2.3899 D(x): 0.7578 D(G(z)): 0.2306 / 0.1154
[3/5][1050/1583] Loss_D: 0.6530 Loss_G: 0.7827 D(x): 0.6068 D(G(z)): 0.0804 / 0.4948
[3/5][1100/1583] Loss_D: 0.4302 Loss_G: 2.5571 D(x): 0.8380 D(G(z)): 0.2001 / 0.1004
[3/5][1150/1583] Loss_D: 0.6501 Loss_G: 3.2462 D(x): 0.6211 D(G(z)): 0.0624 / 0.0671
[3/5][1200/1583] Loss_D: 0.5330 Loss_G: 2.4453 D(x): 0.6936 D(G(z)): 0.1084 / 0.1201
[3/5][1250/1583] Loss_D: 0.6579 Loss_G: 2.9775 D(x): 0.8064 D(G(z)): 0.3086 / 0.0729
[3/5][1300/1583] Loss_D: 0.8314 Loss_G: 1.4531 D(x): 0.5204 D(G(z)): 0.0707 / 0.2779
[3/5][1350/1583] Loss_D: 0.5915 Loss_G: 3.2622 D(x): 0.7783 D(G(z)): 0.2401 / 0.0545
[3/5][1400/1583] Loss_D: 0.4590 Loss_G: 2.6573 D(x): 0.7824 D(G(z)): 0.1690 / 0.0931
[3/5][1450/1583] Loss_D: 0.8523 Loss_G: 1.4182 D(x): 0.5775 D(G(z)): 0.1852 / 0.2888
[3/5][1500/1583] Loss_D: 0.5064 Loss_G: 2.4018 D(x): 0.7946 D(G(z)): 0.2082 / 0.1155
[3/5][1550/1583] Loss_D: 0.4613 Loss_G: 2.9986 D(x): 0.8390 D(G(z)): 0.2231 / 0.0648
[4/5][0/1583] Loss_D: 0.5636 Loss_G: 2.9812 D(x): 0.8497 D(G(z)): 0.2992 / 0.0663
[4/5][50/1583] Loss_D: 0.4695 Loss_G: 2.4989 D(x): 0.8139 D(G(z)): 0.2024 / 0.1020
[4/5][100/1583] Loss_D: 0.9670 Loss_G: 1.4120 D(x): 0.4555 D(G(z)): 0.0352 / 0.3056
[4/5][150/1583] Loss_D: 0.9720 Loss_G: 0.8678 D(x): 0.5019 D(G(z)): 0.1076 / 0.4680
[4/5][200/1583] Loss_D: 0.4589 Loss_G: 2.9348 D(x): 0.8396 D(G(z)): 0.2210 / 0.0712
[4/5][250/1583] Loss_D: 2.4968 Loss_G: 5.8796 D(x): 0.9822 D(G(z)): 0.8533 / 0.0062
[4/5][300/1583] Loss_D: 0.4840 Loss_G: 2.4436 D(x): 0.8053 D(G(z)): 0.2091 / 0.1079
[4/5][350/1583] Loss_D: 1.2550 Loss_G: 1.0989 D(x): 0.3725 D(G(z)): 0.0589 / 0.4122
[4/5][400/1583] Loss_D: 0.5493 Loss_G: 1.5595 D(x): 0.6537 D(G(z)): 0.0745 / 0.2592
[4/5][450/1583] Loss_D: 0.5888 Loss_G: 3.9213 D(x): 0.8947 D(G(z)): 0.3465 / 0.0285
[4/5][500/1583] Loss_D: 0.4694 Loss_G: 2.5386 D(x): 0.8147 D(G(z)): 0.2043 / 0.1020
[4/5][550/1583] Loss_D: 1.2557 Loss_G: 5.5331 D(x): 0.9767 D(G(z)): 0.6419 / 0.0063
[4/5][600/1583] Loss_D: 0.5181 Loss_G: 2.9692 D(x): 0.7998 D(G(z)): 0.2227 / 0.0650
[4/5][650/1583] Loss_D: 0.8944 Loss_G: 4.8075 D(x): 0.9566 D(G(z)): 0.5168 / 0.0128
[4/5][700/1583] Loss_D: 0.6436 Loss_G: 1.8873 D(x): 0.7458 D(G(z)): 0.2502 / 0.1947
[4/5][750/1583] Loss_D: 0.8237 Loss_G: 1.8366 D(x): 0.5554 D(G(z)): 0.1064 / 0.2020
[4/5][800/1583] Loss_D: 0.6184 Loss_G: 1.8781 D(x): 0.6552 D(G(z)): 0.1199 / 0.1953
[4/5][850/1583] Loss_D: 0.6576 Loss_G: 2.5079 D(x): 0.7813 D(G(z)): 0.2901 / 0.1053
[4/5][900/1583] Loss_D: 0.7429 Loss_G: 2.5409 D(x): 0.7202 D(G(z)): 0.2810 / 0.1014
[4/5][950/1583] Loss_D: 0.4859 Loss_G: 2.4504 D(x): 0.8476 D(G(z)): 0.2496 / 0.1114
[4/5][1000/1583] Loss_D: 0.5257 Loss_G: 2.8540 D(x): 0.8695 D(G(z)): 0.2927 / 0.0746
[4/5][1050/1583] Loss_D: 0.9841 Loss_G: 1.6212 D(x): 0.4999 D(G(z)): 0.0871 / 0.2678
[4/5][1100/1583] Loss_D: 0.3802 Loss_G: 2.2152 D(x): 0.8085 D(G(z)): 0.1284 / 0.1415
[4/5][1150/1583] Loss_D: 0.8692 Loss_G: 1.6206 D(x): 0.7177 D(G(z)): 0.3184 / 0.2517
[4/5][1200/1583] Loss_D: 0.3829 Loss_G: 2.4155 D(x): 0.8827 D(G(z)): 0.2053 / 0.1126
[4/5][1250/1583] Loss_D: 0.5252 Loss_G: 2.5692 D(x): 0.8169 D(G(z)): 0.2462 / 0.0945
[4/5][1300/1583] Loss_D: 0.3760 Loss_G: 3.1783 D(x): 0.9039 D(G(z)): 0.2187 / 0.0553
[4/5][1350/1583] Loss_D: 0.9568 Loss_G: 3.7607 D(x): 0.9022 D(G(z)): 0.5128 / 0.0364
[4/5][1400/1583] Loss_D: 0.4138 Loss_G: 3.2217 D(x): 0.8748 D(G(z)): 0.2194 / 0.0519
[4/5][1450/1583] Loss_D: 1.3934 Loss_G: 5.6238 D(x): 0.9508 D(G(z)): 0.6783 / 0.0064
[4/5][1500/1583] Loss_D: 0.6086 Loss_G: 2.7344 D(x): 0.8207 D(G(z)): 0.3006 / 0.0855
[4/5][1550/1583] Loss_D: 1.1754 Loss_G: 0.7604 D(x): 0.3890 D(G(z)): 0.0385 / 0.5090
Results¶
Finally, lets check out how we did. Here, we will look at three different results. First, we will see how D and G’s losses changed during training. Second, we will visualize G’s output on the fixed_noise batch for every epoch. And third, we will look at a batch of real data next to a batch of fake data from G.
Loss versus training iteration
Below is a plot of D & G’s losses versus training iterations.

Visualization of G’s progression
Remember how we saved the generator’s output on the fixed_noise batch after every epoch of training. Now, we can visualize the training progression of G with an animation. Press the play button to start the animation.
fig = plt.figure(figsize=(8,8))
plt.axis("off")
ims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]
ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)
HTML(ani.to_jshtml())
